package ServiceProvider;

import javax.jms.*;
import javax.naming.InitialContext;

public class Publisher {

	private static final String TOPIC_CONNECTION_FACTORY = "TopicCF";
	private InitialContext ctx;
	private TopicSession pubSession;
	private TopicPublisher publisher;
	private TopicConnection connection;
	
	public Publisher() {
		try {
			this.ctx = new InitialContext();
			TopicConnectionFactory conFactory =
					(TopicConnectionFactory) this.ctx.lookup(TOPIC_CONNECTION_FACTORY);
			this.connection = conFactory.createTopicConnection();
			this.pubSession = this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void connectTopic(String topicName) {
		try {
			Topic topic = (Topic) this.ctx.lookup(topicName);
			this.publisher = this.pubSession.createPublisher(topic);
			this.connection.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void publishMessage(String text){
		try {
			TextMessage message = pubSession.createTextMessage();
			message.setText("Admin: " + text);
			this.publisher.publish(message);
			System.out.println("Publish successful");
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
